package com.hexiang.web;

import java.io.StringWriter;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import com.hexiang.domain.User;
import com.hexiang.service.MailService;

import freemarker.template.Configuration;
import freemarker.template.Template;

@RestController
public class MailController {
    @Autowired
    MailService mailService;

    @Autowired
    TemplateEngine templateEngine;

    @GetMapping("/sendSimpleMail")
    public void sendSimpleMail() {
        mailService.sendSimpleMail("123@QQ.com", "hangge@163.com", "service@hangge.com", "我是邮件的标题", "我是邮件的内容");
    }

    @GetMapping("/sendHtmlMailByFreeMarker")
    public void sendHtmlMailByFreeMarker() {
        try {
            // 首先配置 FreeMarker 模版位置
            Configuration configuration = new Configuration(Configuration.VERSION_2_3_0);
            ClassLoader loader = MailController.class.getClassLoader();
            configuration.setClassLoaderForTemplateLoading(loader, "ftl");

            // 配置模版文件
            Template template = configuration.getTemplate("mailtemplate.ftl");

            // 结合 User 对象渲染模版
            StringWriter mail = new StringWriter();
            User user = new User();
            user.setUserName("hangge");
            template.process(user, mail);

            // 将渲染结果发送出去
            mailService.sendHtmlMail("123@qq.com", "service@hangge.com", "这个是邮件的标题", mail.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @GetMapping("/sendHtmlMailByThymeleaf")
    public void sendHtmlMailByThymeleaf() {
        // 通过 Context 构造模版中变量需要的值
        Context ctx = new Context();
        ctx.setVariable("username", "hangge");
        ctx.setVariable("sex", "男");

        // 使用TemplateEngine 对模版进行渲染
        String mail = templateEngine.process("mailtemplate.html", ctx);

        // 将渲染结果通过邮件发出
        mailService.sendHtmlMail("380552225@qq.com", "yuhang0385@163.com", "这个是邮件的标题", mail);
    }
}